#!/bin/bash

# 设置错误时退出
set -e

# 确保配置主目录存在
if [ -z "$CONFIG_HOME" ]; then
  export CONFIG_HOME="${HOME}/.mac_sync"
fi

# 加载日志工具
if [ -f "${CONFIG_HOME}/log_utils.zsh" ]; then
  source "${CONFIG_HOME}/log_utils.zsh"
fi

# 固定为Node.js 14版本环境
NODE_VERSION="14"

# 设置日志文件
LOG_FILE="${CONFIG_HOME}/logs/node_legacy_setup_$(date +%Y%m%d_%H%M%S).log"
mkdir -p "$(dirname "$LOG_FILE")"

# 日志函数（如果log_utils.zsh不可用）
if ! type log_info > /dev/null 2>&1; then
  log_info() {
    echo "ℹ️ [$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
  }
  
  log_success() {
    echo "✅ [$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
  }
  
  log_error() {
    echo "❌ [$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
  }

  log_warning() {
    echo "⚠️ [$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
  }
  
  log_header() {
    echo ""
    echo "=== $1 ===" | tee -a "$LOG_FILE"
  }
  
  log_node() {
    echo "📦 Node.js: $1" | tee -a "$LOG_FILE"
  }
  
  log_npm() {
    echo "📦 npm: $1" | tee -a "$LOG_FILE"
  }
  
  log_pnpm() {
    echo "📦 pnpm: $1" | tee -a "$LOG_FILE"
  }
  
  log_path() {
    echo "🔍 $1: $2" | tee -a "$LOG_FILE"
  }
fi

# 使用统一的全局包根目录结构
NODE_GLOBAL_ROOT="${HOME}/.node_global"
GROUP="legacy"
NPM_GLOBAL_DIR="${NODE_GLOBAL_ROOT}/${GROUP}/npm"
PNPM_GLOBAL_DIR="${NODE_GLOBAL_ROOT}/${GROUP}/pnpm"

# 创建目录
mkdir -p "${NPM_GLOBAL_DIR}/bin"
mkdir -p "${PNPM_GLOBAL_DIR}/bin"
mkdir -p "${PNPM_GLOBAL_DIR}/store"
chmod 755 "${NPM_GLOBAL_DIR}"
chmod 755 "${PNPM_GLOBAL_DIR}"

# 记录当前环境变量
ORIGINAL_NPM_PREFIX=$(npm config get prefix)
ORIGINAL_PATH=$PATH

# 临时设置环境变量
export NPM_CONFIG_PREFIX="${NPM_GLOBAL_DIR}"
export PATH="${NPM_GLOBAL_DIR}/bin:$PATH"

log_header "开始安装 Node.js ${NODE_VERSION}.x 兼容性环境"
log_info "全局工具将安装到: ${NPM_GLOBAL_DIR}"

# 清理之前的失败记录
FAILED_PACKAGES_FILE="${CONFIG_HOME}/logs/node_legacy_failed_packages.txt"
rm -f "$FAILED_PACKAGES_FILE"

# 安装包函数
install_package() {
    local package=$1
    local version=$2
    local full_package="${package}@${version}"
    
    log_info "正在安装 ${full_package}..."
    if npm install -g "${full_package}" >> "$LOG_FILE" 2>&1; then
        log_success "${full_package} 安装完成"
        return 0
    else
        log_error "${full_package} 安装失败"
        echo "${full_package}" >> "$FAILED_PACKAGES_FILE"
        return 1
    fi
}

# 基础开发工具（选择稳定版本）
log_header "基础开发工具"
install_package "typescript" "4.6.4"
install_package "nodemon" "2.0.15"
install_package "pm2" "5.1.2"
install_package "http-server" "14.0.0"
install_package "serve" "13.0.2"
install_package "json-server" "0.17.0"

# 前端框架 CLI（选择兼容版本）
log_header "前端框架 CLI"
install_package "@vue/cli" "4.5.15"
install_package "@angular/cli" "13.3.9"
install_package "create-react-app" "4.0.3"
install_package "gatsby-cli" "4.25.0"

# 构建工具（选择稳定版本）
log_header "构建工具"
install_package "yarn" "1.22.19"
install_package "webpack-cli" "4.9.2"
install_package "rollup" "2.70.2"
install_package "parcel" "2.8.3"

# 工具链
log_header "工具链"
install_package "eslint" "8.15.0"
install_package "prettier" "2.6.2"
install_package "typescript-eslint" "0.0.1-alpha.0"
install_package "commitizen" "4.2.4"
install_package "husky" "7.0.4"
install_package "lint-staged" "12.4.1"

# CSS 预处理器
log_header "CSS 预处理器"
install_package "sass" "1.51.0"
install_package "less" "4.1.2"

# 测试工具
log_header "测试工具"
install_package "jest" "27.5.1"
install_package "cypress" "9.7.0"

# 文档工具
log_header "文档工具"
install_package "docsify-cli" "4.4.4"
install_package "jsdoc" "3.6.10"

# 安装 pnpm@6（与node_env.zsh一致）
log_header "包管理器"
install_package "pnpm" "6.32.24"

# 配置 pnpm
export PNPM_HOME="${PNPM_GLOBAL_DIR}"
export PATH="${PNPM_HOME}/bin:$PATH"
pnpm config set global-dir "${PNPM_HOME}"
pnpm config set global-bin-dir "${PNPM_HOME}/bin"
pnpm config set store "${PNPM_HOME}/store"
log_success "pnpm 配置完成"

# 恢复原始环境变量
export PATH="$ORIGINAL_PATH"
npm config set prefix "$ORIGINAL_NPM_PREFIX"

# 检查是否有安装失败的包
if [ -f "$FAILED_PACKAGES_FILE" ]; then
    log_warning "以下包安装失败："
    cat "$FAILED_PACKAGES_FILE" | tee -a "$LOG_FILE"
    log_warning "您可以稍后尝试手动安装这些包"
else
    log_success "所有包安装成功！"
fi

log_success "Node.js ${NODE_VERSION}.x 兼容性环境配置完成！"
log_info "安装日志已保存到：$LOG_FILE"

log_header "环境配置信息"
log_path "Node.js 版本" "${NODE_VERSION}"
log_path "分组" "${GROUP}"
log_path "npm 全局工具安装目录" "${NPM_GLOBAL_DIR}"
log_path "pnpm 全局目录" "${PNPM_GLOBAL_DIR}"

log_header "使用方式"
log_info "1. 当使用'n ${NODE_VERSION}'切换到Node.js ${NODE_VERSION}时，会自动使用此分组的全局包"
log_info "2. 全局工具将自动可用，不需要额外配置"
log_info "3. 使用 'node-global' 命令可查看当前全局包目录信息" 